package com.hulman.oms.web;

import com.hulman.oms.bean.Dict;
import com.hulman.oms.bean.DictItem;
import com.hulman.oms.bean.Result;
import com.hulman.oms.service.DictItemService;
import com.hulman.oms.service.DictService;
import com.hulman.oms.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class DictController
{
    @Autowired
    private DictService dictService;
    @Autowired
    private DictItemService dictItemService;

    @GetMapping("/dicts/{id}")
    public Result findDictById(@PathVariable Integer id)
    {
        Dict dict = dictService.findDictById(id);
        return new Result(dict);
    }

    @GetMapping("/dicts")
    public Result findDicts(Integer page, Integer limit, String name, String key, Integer state)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("name", name);
        map.put("key", key);
        map.put("state", state);
        return dictService.findDictsResult(map);
    }

    @DeleteMapping("/dicts/{ids}")
    public Result deleteDictById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            dictItemService.deleteDictItemById(id);
        }
        return Result.SUCCESS;
    }

    @PutMapping("/dicts")
    public Result saveDict(Dict dict)
    {
        dictService.saveDict(dict);
        return Result.SUCCESS;
    }

	/**
	 * 根据字典键名查找所有选项
	 * @param dictKey
	 * @return
	 */
	@GetMapping("/dicts/items/{dictKey}")
	public Result findDictByDictKey(@PathVariable String dictKey)
	{
		return dictItemService.findDictItemsResultByDictKey(dictKey);
	}

    /**
     * 删除字典项
     * @param id
     * @return
     */
	@DeleteMapping("/dict-items/{id}")
	public Result deleteDictItemById(@PathVariable Integer id)
	{
		dictItemService.deleteDictItemById(id);
		return Result.SUCCESS;
	}

    /**
     * 修改字典项
     * @param dictItem
     * @return
     */
	@PutMapping("/dict-items")
	public Result saveDictItem(DictItem dictItem)
	{
		dictItemService.saveDictItem(dictItem);
		return Result.SUCCESS;
	}

}
